package com.yangjun.service.report;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.yangjun.common.ServerResponse;
import com.yangjun.dao.mybatis.mapper.report.ReportDownloadStatusMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportExportStatusMapper;
import com.yangjun.entity.report.DvReportDownloadStatusEntity;
import com.yangjun.entity.report.DvReportExportStatus;
import com.yangjun.utils.DvDateUtils;
import com.yangjun.vo.report.ActivePackageReportExportVO;
import com.yangjun.vo.report.CommodityFlowReportExportVO;
import com.yangjun.vo.report.DownloadReportVO;
import com.yangjun.vo.report.OrderTransactionReportExportVO;
import com.yangjun.vo.report.ProductInfoReportExportVO;
import com.yangjun.vo.report.SingleProductReportExportVO;
import com.yangjun.vo.report.StoragePeriodReportExportVO;
import com.yangjun.vo.report.TMallRxReportExportVO;
import com.yangjun.vo.report.TargetMemberReportExportVO;

@Service
public class DownLoadService {
	@Value("${excel.downloadPath}")
    private String downloadPath;
	@Autowired
	private ReportDownloadStatusMapper reportDownloadStatusMapper;
	@Autowired
	private ReportExportStatusMapper reportExportStatusMapper;
	@Autowired
	private SingleProductReprotExportService singleProductReprotExportService;
	@Autowired
	private ProductInfoReprotExportService productInfoReprotExportService;
	@Autowired
	private CommodityFlowReprotExportService commodityFlowReprotExportService;
	@Autowired
	private TargetMemberReprotExportService targetMemberReprotExportService;
	@Autowired
	private TMallRxReprotExportService tMallRxReprotExportService;
	@Autowired
	private ActivePackageReprotExportService activePackageReprotExportService;
	@Autowired
	private StoragePeriodReprotExportService storagePeriodReprotExportService;
	@Autowired
	private OrderTransactionReprotExportService orderTransactionReprotExportService;
	public Object queryDownloadList(String userid){
		//删除三天之前的记录
		reportDownloadStatusMapper.deleteReportByDate(userid, DvDateUtils.getDate(new Date(), -3));
		
		List<DownloadReportVO> resultList = Lists.newArrayList();
		List<DvReportDownloadStatusEntity> dvReportDownloadStatusList = reportDownloadStatusMapper.queryReportByUserid(userid);
		for(DvReportDownloadStatusEntity dvReportDownloadStatusItem : dvReportDownloadStatusList){
			DownloadReportVO downloadReportVO = new DownloadReportVO();
			downloadReportVO.setUserid(dvReportDownloadStatusItem.getUserid());
			downloadReportVO.setBeginDate(DvDateUtils.format(dvReportDownloadStatusItem.getBeginDate(),"yyyy-MM-dd HH:mm:ss"));
			downloadReportVO.setEndDate(dvReportDownloadStatusItem.getEndDate()==null?"--":DvDateUtils.format(dvReportDownloadStatusItem.getEndDate(),"yyyy-MM-dd HH:mm:ss"));
			downloadReportVO.setDataDate(DvDateUtils.format(dvReportDownloadStatusItem.getDataDate(),"yyyy-MM-dd HH:mm:ss"));
			downloadReportVO.setDownloadId(dvReportDownloadStatusItem.getDownloadId());
			downloadReportVO.setFileName(dvReportDownloadStatusItem.getFileName());
			downloadReportVO.setReportName(dvReportDownloadStatusItem.getReportName());
			downloadReportVO.setTimeConsume(dvReportDownloadStatusItem.getTimeConsume());
			downloadReportVO.setDownloadFlag(dvReportDownloadStatusItem.getDownloadFlag());
			resultList.add(downloadReportVO);
		}
		return ServerResponse.createBySuccess(resultList);
	}

	public Object downloadReport(String reportName,String fileName,HttpServletResponse response){
			byte[] buff = new byte[1024];
			BufferedInputStream bis = null;
			OutputStream os = null;
			BufferedOutputStream bos = null;
			try {
				reportName = reportName+".xlsx";
				response.setHeader("conent-type", "application/octet-stream");  
	            response.setContentType("application/octet-stream"); 
				response.setHeader("Content-Disposition", "attachment;filename=" + new String( reportName.getBytes("UTF-8"), "ISO8859-1" ));
				os = response.getOutputStream();
				bos = new BufferedOutputStream(os);  
				bis = new BufferedInputStream(new FileInputStream(new File(downloadPath+fileName)));
				int length = 0;
				while((length = bis.read(buff))!=-1){
					bos.write(buff, 0, length);
				}
				bos.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(bis!=null){
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(bos!=null){
					try {
						bos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return ServerResponse.createBySuccessMessage("下载成功！");
	}
	
	public Object deleteAll(String userid){
		if(reportDownloadStatusMapper.deleteReportByUserid(userid)>0){
			List<DvReportDownloadStatusEntity> deleteReportList = reportDownloadStatusMapper.queryDeleteReportByUserid(userid);
			if(deleteReportList.size()>0){
				for(DvReportDownloadStatusEntity dvReportDownloadStatusEntity: deleteReportList){
					String fileName = dvReportDownloadStatusEntity.getFileName();
					File file = new File(downloadPath+fileName);
					if(file.isFile()&&file.exists()){
						file.delete();
					}
				}
			}
			return ServerResponse.createBySuccessMessage("删除成功！");
		}
		return ServerResponse.createByErrorMessage("删除失败！");
	}
	
	
	public Object addDownloadTaskImmediately(String reportid,HttpServletRequest request){
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		String reporttype = dvReportExportStatus.getReporttype();
		if("productInfo".equals(reporttype)){
			ProductInfoReportExportVO pireVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ProductInfoReportExportVO.class);
			return productInfoReprotExportService.download(pireVo,request);
		}else if("commodityFlow".equals(reporttype)){
			CommodityFlowReportExportVO cfreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), CommodityFlowReportExportVO.class);
			return commodityFlowReprotExportService.download(cfreVo,request);
		}else if("singleProduct".equals(reporttype)){
			SingleProductReportExportVO spreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), SingleProductReportExportVO.class);
			return singleProductReprotExportService.download(spreVo,request);
		}else if("tmallRx".equals(reporttype)){
			TMallRxReportExportVO tmrxreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), TMallRxReportExportVO.class);
			return tMallRxReprotExportService.download(tmrxreVo,request);
		}else if("targetMember".equals(reporttype)){
			TargetMemberReportExportVO tmreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), TargetMemberReportExportVO.class);
			return targetMemberReprotExportService.download(tmreVo,request);
		}else if("activePackage".equals(reporttype)){
			ActivePackageReportExportVO apreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ActivePackageReportExportVO.class);
			return activePackageReprotExportService.download(apreVo,request);
		}else if("orderTransaction".equals(reporttype)){
			OrderTransactionReportExportVO otreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), OrderTransactionReportExportVO.class);
			return orderTransactionReprotExportService.download(otreVo,request);
		}else if("storagePeriod".equals(reporttype)){
			StoragePeriodReportExportVO spreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), StoragePeriodReportExportVO.class);
			return storagePeriodReprotExportService.download(spreVo,request);
		}
		return ServerResponse.createByErrorMessage("加入下载任务失败");
	}
}
